package com.butte.mound.frame.token;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.butte.mound.frame.security.AuthCheck;
import java.util.Arrays;
import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Component;

@Component
public class BaseToken {

  @Getter
  @Setter
  private Long userId;

  @Getter
  @Setter
  private String userName;

  @Getter
  @Setter
  private String appName;

  @Getter
  @Setter
  private Long expireTime;

  private static final byte[] AES_KEY = Arrays.copyOf(MD5.create().digest(BaseToken.class.getPackage().getName()), 16);

  @Getter
  private final String currentType = BaseToken.class.getTypeName();

  public void expireTime(int effective) {
    expireTime = System.currentTimeMillis()/1000 + effective ;
  }

  public boolean expired() {
    return expireTime < (System.currentTimeMillis() / 1000);
  }

  public String toToken() {
    String data = JSONUtil.toJsonStr(this);
    return SecureUtil.aes(AES_KEY).encryptBase64(data);
  }

  public static BaseToken parseToken(String token) {
    String dataStr = SecureUtil.aes(AES_KEY).decryptStr(token);
    return JSONUtil.toBean(dataStr, BaseToken.class);
  }

  public boolean checkPermission (String... permissionCode) {
    AuthCheck authService = SpringUtil.getBean(AuthCheck.class);
    return authService.hasPermission(this.getUserId(), permissionCode);
  }

  public static void main(String[] args) {
    BaseToken baseToken = new BaseToken();
    baseToken.setUserId(1L);
    baseToken.setUserName("facade-user");
    baseToken.setAppName("facade");
    baseToken.setExpireTime(10000L);

    System.out.println(baseToken.toToken());

    BaseToken baseToken2 = new BaseToken();
    baseToken2.setUserId(1L);
    baseToken2.setUserName("admin-user");
    baseToken2.setAppName("admin");
    baseToken2.setExpireTime(10000L);

    System.out.println(baseToken2.toToken());
  }

}
